Branchwell

Lumen & Gesso / website · lumengesso.com / app / orders / [id] / page.tsx

1import Link from 'next/link';
2import { notFound, redirect } from 'next/navigation';
3import { getCustomerUser } from '@/app/lib/lumen-auth';
4import { commerceDb } from '@/app/lib/commerce-db';
5import { displayOrderId } from '@/app/lib/orders';
6import { STYLE_CATALOG } from '@/app/data/styleCatalog';
7import { BACKGROUND_COLORS } from '@/app/data/backgrounds';
8import { PRODUCTS, sizeLabel, type Orientation } from '@/app/lib/pricing';
9import { FramedPreview } from '@/app/components/FramedPreview';
10import type { FrameId } from '@/app/data/frames';
11import { CancelButton } from './cancel-button';
12import { OrderConversation } from '@/app/components/OrderConversation';
13import { CustomerOrderMessageForm } from '@/app/components/CustomerOrderMessageForm';
14import { orderConversation, STUDIO_MESSAGE_STATUSES } from '@/app/lib/order-messages';
15import { REVIEWABLE_STATUSES } from '@/app/lib/reviews';
16import { ReviewForm } from './review-form';
17
18export const dynamic = 'force-dynamic';
19
20// Label maps for the picker-time selections stored in order.config.
21// Kept inline here to avoid pulling the Builder's full FRAME/MATTE/FONT
22// definitions (which carry gradients + font CSS) into a server bundle
23// that only needs labels.
24const FRAME_LABELS: Record<string, string> = {
25 black: 'Matte black', white: 'Soft white', walnut: 'Walnut',
26 oak: 'Honey oak', gold: 'Warm gold', silver: 'Brushed silver',
27};
28const MATTE_LABELS: Record<string, string> = {
29 snowwhite: 'Snow white',
30 offwhite: 'Off-white',
31 black: 'Black',
32 // Legacy values that may exist on older orders:
33 warmwhite: 'Off-white', // renamed
34 hayseed: 'Off-white',
35 cream: 'Off-white',
36 none: 'Snow white',
37};
38const FONT_LABELS: Record<string, string> = {
39 modern: 'Modern', editorial: 'Editorial', display: 'Display',
40 italic: 'Italic', serif: 'Classic', script: 'Script',
41 hand: 'Handwritten', soft: 'Soft sans',
42};
43
44type OrderConfig = {
45 workflow?: string;
46 styleId?: string;
47 productId?: 'matted' | 'canvas' | 'classic' | 'stretched';
48 size?: string;
49 orientation?: Orientation;
50 frame?: string;
51 matteId?: string;
52 bgColorId?: string;
53 bgCustom?: string;
54 fontId?: string;
55 includeName?: boolean;
56 commissionName?: string | null;
57 artistNote?: string;
58 pets?: Array<{ slot: number; name: string | null }>;
59 customerCancellation?: { state?: 'pending' | 'refunded' | 'unpaid' };
60};
61
62export default async function OrderDetailPage(
63 { params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ revised?: string }> },
64) {
65 const { id } = await params;
66 const { revised } = await searchParams;
67 const user = await getCustomerUser();
68 if (!user) redirect(`/login?next=/orders/${id}`);
69
70 const admin = commerceDb();
71 const { data: order } = await admin
72 .from('orders')
73 .select('*')
74 .eq('id', id)
75 .single();
76
77 if (!order) notFound();
78 if (order.user_id !== user.id) notFound();
79
80 // pending_payment / abandoned are pre-studio rows where Stripe was
81 // never completed. Send the customer to the resume-payment screen
82 // so they can pay (or back out) instead of staring at a useless
83 // detail page.
84 const cfg = (order.config as OrderConfig | null) ?? {};
85 const selfServicePrint = cfg.workflow === 'self_service_print_v1';
86 if (!selfServicePrint && (order.status === 'pending_payment' || order.status === 'abandoned')) {
87 redirect(`/checkout?orderId=${order.id}&canceled=1`);
88 }
89
90 // Once the customer has approved (status >= approved), show the
91 // actual final framed artwork on the order detail page.
92 const POST_APPROVAL_STATUSES = new Set(['approved', 'fulfillment_submitting', 'fulfillment_review', 'in_production', 'shipped']);
93 let approvedCleanUrl: string | null = null;
94 if (POST_APPROVAL_STATUSES.has(order.status as string) && order.current_generation_id) {
95 const { data: gen } = await admin
96 .from('generations')
97 .select('clean_url')
98 .eq('id', order.current_generation_id)
99 .single();
100 approvedCleanUrl = gen?.clean_url ?? null;
101 }
102
103 const status = order.status as string;
104 const reviewable = REVIEWABLE_STATUSES.includes(status);
105 const review = reviewable
106 ? await admin.from('order_reviews').select('status').eq('order_id', order.id).maybeSingle()
107 : null;
108 const style = STYLE_CATALOG.find(s => s.id === cfg.styleId);
109 const product = cfg.productId ? PRODUCTS[cfg.productId] : null;
110 const sizes = product?.sizes as Record<string, { label: string; aspect: string }> | undefined;
111 const sizeMeta = sizes && cfg.size ? sizes[cfg.size] : undefined;
112 const orientation = cfg.orientation ?? 'portrait';
113 // Transposed for landscape orders ('10 × 8 in'); sizeMeta stays the
114 // existence check, sizeLabelStr is what we display.
115 const sizeLabelStr = sizeLabel(cfg.productId, cfg.size, orientation);
116 const frameLabel = cfg.frame ? FRAME_LABELS[cfg.frame] : null;
117 const hasMatOption = cfg.productId === 'matted' || cfg.productId === 'classic';
118 const matteLabel = hasMatOption && cfg.matteId ? cfg.matteId === 'nomat' ? 'No mat' : MATTE_LABELS[cfg.matteId] : null;
119 const cancellationState = cfg.customerCancellation?.state;
120 const bgLabel = cfg.bgColorId === 'custom'
121 ? (cfg.bgCustom || 'Custom')
122 : (cfg.bgColorId ? BACKGROUND_COLORS[cfg.bgColorId as keyof typeof BACKGROUND_COLORS]?.label : null);
123 const fontLabel = cfg.includeName && cfg.fontId ? FONT_LABELS[cfg.fontId] : null;
124 const petNames = (cfg.pets ?? []).map(p => p.name).filter((n): n is string => !!n);
125 const photos = (order.pet_photo_urls as string[]) ?? [];
126 const customStyleUrl = (order.custom_style_url as string | null) ?? null;
127 const artistNote = (cfg.artistNote ?? '').trim();
128 const messages = orderConversation(order.config, order.revision_note, order.updated_at);
129 const canMessage = STUDIO_MESSAGE_STATUSES.includes(status);
130
131 return (
132 <main className="orders">
133 <div className="orders__inner">
134 <Link href="/orders" className="orders__back">← All commissions</Link>
135 <h1 className="orders__title">{displayOrderId(order.id)}</h1>
136
137 <div className="orderdetail">
138 <div className={`orderdetail__status orderdetail__status--${status}`}>
139 <span className={`statuschip statuschip--${status}`}>{statusLabel(status)}</span>
140 <p className="orderdetail__statusbody">{status === 'cancelled'
141 ? cancellationState === 'pending' ? 'Your commission is cancelled. Your refund has not been confirmed yet.'
142 : cancellationState === 'refunded' ? 'Your commission is cancelled and a refund has been requested.'
143 : 'Your commission is cancelled.'
144 : selfServicePrint && status === 'pending_payment'
145 ? 'We haven’t confirmed payment yet. If you already paid, do not pay again. Refresh this page in a moment to check the status.'
146 : statusBody(status, order.id)}</p>
147 {status === 'shipped' && (order.tracking_number || order.tracking_url) && (
148 <p className="orderdetail__statusbody" style={{ marginTop: 10, fontWeight: 500 }}>
149 {order.carrier ? `${order.carrier} · ` : ''}
150 {order.tracking_number ? <strong>{order.tracking_number}</strong> : null}
151 {order.tracking_url ? (
152 <>
153 {' '}·{' '}
154 <a href={order.tracking_url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--rose-deep)' }}>
155 Track shipment →
156 </a>
157 </>
158 ) : null}
159 </p>
160 )}
161 {status === 'awaiting_approval' && (
162 <div className="orderdetail__cta">
163 <Link href={`/orders/${order.id}/approve`} className="btn btn--rose btn--md">
164 Review your proof →
165 </Link>
166 </div>
167 )}
168 {(status === 'pending_design' || status === 'awaiting_approval' || status === 'revision_requested' || status === 'cancelled' && cancellationState === 'pending') && (
169 <CancelButton orderId={order.id} priceCents={order.price_cents} paid={!!order.stripe_payment_intent_id}
170 refundPending={status === 'cancelled' && cancellationState === 'pending'} />
171 )}
172 {status === 'cancelled' && photos.length > 0 && <div className="orderdetail__cta">
173 <Link href={`/builder?edit=${encodeURIComponent(order.id)}&replace=1`} className="btn btn--rose btn--md">Start a replacement</Link>
174 {' '}<Link href="/orders/photos" className="btn btn--secondary btn--md">Saved photos</Link>
175 </div>}
176 </div>
177
178 {(messages.length > 0 || canMessage) && (
179 <div id="conversation" className="orderdetail__revisions">
180 <OrderConversation messages={messages}>
181 {canMessage && <CustomerOrderMessageForm orderId={order.id} proofId={status === 'awaiting_approval' ? order.current_generation_id ?? undefined : undefined} />}
182 </OrderConversation>
183 {status === 'revision_requested' && revised === 'saved' && (
184 <p role="status">Your request is saved here. We couldn’t email the studio a notification.</p>
185 )}
186 </div>
187 )}
188
189 {reviewable && (
190 <section id="review" className="admin-editor__panel order-review" aria-labelledby="leave-review">
191 <h2 className="orderdetail__photoshead" id="leave-review">Leave a review</h2>
192 {review?.error ? <p>Reviews are temporarily unavailable. Please try again later.</p>
193 : review?.data ? <p>{review.data.status === 'approved' ? 'Thank you. Your review is published.' : 'Thank you. We’ve received your review.'}</p>
194 : <ReviewForm orderId={order.id} />}
195 </section>
196 )}
197
198 {approvedCleanUrl && (
199 <div className="orderdetail__framed">
200 <FramedPreview
201 src={approvedCleanUrl}
202 alt="Your approved portrait in your chosen frame"
203 productId={cfg.productId ?? 'matted'}
204 size={cfg.size ?? '12x16'}
205 orientation={orientation}
206 frame={(cfg.frame ?? 'black') as FrameId}
207 matteId={cfg.matteId ?? null}
208 />
209 <p className="orderdetail__framednote">
210 Your approved portrait, mocked up in your chosen{' '}
211 <span style={{ whiteSpace: 'nowrap' }}>
212 {product?.label ?? 'frame'}{sizeMeta ? `, ${sizeLabelStr}` : ''}.
213 </span>
214 </p>
215 </div>
216 )}
217
218 <div className="orderdetail__summary">
219 {customStyleUrl ? (
220 <div className="orderdetail__row">
221 <span>Style</span>
222 <span>Custom — your reference</span>
223 </div>
224 ) : style ? (
225 <div className="orderdetail__row">
226 <span>Style</span>
227 <span>{style.name}</span>
228 </div>
229 ) : null}
230 {product && sizeMeta && (
231 <div className="orderdetail__row">
232 <span>Product</span>
233 <span>{product.label}, {sizeLabelStr}</span>
234 </div>
235 )}
236 {frameLabel && (
237 <div className="orderdetail__row">
238 <span>Frame</span>
239 <span>{frameLabel}</span>
240 </div>
241 )}
242 {matteLabel && (
243 <div className="orderdetail__row">
244 <span>Mount</span>
245 <span>{matteLabel}</span>
246 </div>
247 )}
248 {bgLabel && (
249 <div className="orderdetail__row">
250 <span>Background</span>
251 <span>{bgLabel}</span>
252 </div>
253 )}
254 {cfg.includeName && cfg.commissionName && (
255 <div className="orderdetail__row">
256 <span>Lettering</span>
257 <span>“{cfg.commissionName}”{fontLabel ? ` · ${fontLabel}` : ''}</span>
258 </div>
259 )}
260 {petNames.length > 0 && (
261 <div className="orderdetail__row">
262 <span>{petNames.length === 1 ? 'Pet' : 'Pets'}</span>
263 <span>{petNames.join(', ')}</span>
264 </div>
265 )}
266 <div className="orderdetail__row">
267 <span>Portrait subtotal</span>
268 <span>${(order.price_cents / 100).toFixed(2)}</span>
269 </div>
270 <div className="orderdetail__row">
271 <span>Submitted</span>
272 <span>{new Date(order.created_at).toLocaleString()}</span>
273 </div>
274 </div>
275
276 {photos.length > 0 && (
277 <div className="orderdetail__photos">
278 <div className="orderdetail__photoshead">
279 Photos you sent <span className="orderdetail__photoscount">· {photos.length}</span>
280 </div>
281 <div className="orderdetail__photosgrid">
282 {photos.map((url, i) => (
283 <a
284 key={url}
285 href={url}
286 target="_blank"
287 rel="noopener noreferrer"
288 className="orderdetail__photothumb"
289 aria-label={`Open pet photo ${i + 1} in a new tab`}
290 >
291 {/* eslint-disable-next-line @next/next/no-img-element */}
292 <img src={url} alt={`Pet photo ${i + 1}`} loading="lazy" />
293 </a>
294 ))}
295 </div>
296 </div>
297 )}
298
299 {customStyleUrl && (
300 <div className="orderdetail__photos">
301 <div className="orderdetail__photoshead">Your style reference</div>
302 <div className="orderdetail__photosgrid">
303 <a
304 href={customStyleUrl}
305 target="_blank"
306 rel="noopener noreferrer"
307 className="orderdetail__photothumb"
308 aria-label="Open your style reference in a new tab"
309 >
310 {/* eslint-disable-next-line @next/next/no-img-element */}
311 <img src={customStyleUrl} alt="Your style reference" loading="lazy" />
312 </a>
313 </div>
314 </div>
315 )}
316
317 {artistNote && (
318 <p className="orderdetail__artistnote">
319 <span className="orderdetail__artistnotelabel">Your note to the artist</span>
320 “{artistNote}”
321 </p>
322 )}
323 </div>
324 </div>
325 </main>
326 );
327}
328
329function statusLabel(s: string): string {
330 switch (s) {
331 // pending_payment / abandoned redirect to /checkout before render,
332 // but label them in case a future code path lands here.
333 case 'pending_payment': return 'Checkout not complete';
334 case 'abandoned': return 'Checkout abandoned';
335 case 'pending_design': return 'In the design queue';
336 case 'awaiting_approval': return 'Proof ready — review';
337 case 'revision_requested': return 'Revision in progress';
338 case 'approved': return 'Approved — final studio review';
339 case 'fulfillment_submitting': return 'Payment received · sending to printer';
340 case 'fulfillment_review': return 'Payment received · checking print order';
341 case 'in_production': return 'In production';
342 case 'shipped': return 'Shipped';
343 case 'cancelled': return 'Cancelled';
344 default: return s;
345 }
346}
347
348function statusBody(status: string, _orderId: string): string {
349 switch (status) {
350 case 'pending_payment':
351 return "We haven't received payment yet. Head back to checkout to finish — your design selections are saved.";
352 case 'abandoned':
353 return "Checkout was never completed. Head back to checkout to pick up where you left off — or start a fresh commission.";
354 case 'pending_design':
355 return "Our studio is hand-crafting your proof. We typically have a first draft ready within 24 hours — we'll email you when it's time to review.";
356 case 'awaiting_approval':
357 return "Your proof is ready. Open it to approve and pay, or request revisions — free, until it's right.";
358 case 'revision_requested':
359 return "We're working on your revision. Expect another proof within 24 hours.";
360 case 'approved':
361 return "You approved your portrait — our studio is doing one final review before sending it to print. You'll get a confirmation email when it goes to the printer.";
362 case 'fulfillment_submitting':
363 return "Payment is confirmed. We’re sending the exact image you approved to the printer.";
364 case 'fulfillment_review':
365 return "Payment is confirmed. We couldn’t verify printer acceptance yet. Don’t place a second order.";
366 case 'in_production':
367 return "Your portrait is being printed and framed. Ships within 10 days.";
368 case 'shipped':
369 return "On the way to you.";
370 case 'cancelled':
371 return "This commission was cancelled and a full refund is on its way back to your card. Refunds typically take 5–10 business days to land.";
372 default:
373 return '';
374 }
375}